package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.common.query.QueryObject;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.repository.IStrategyTemplateRepository;
import cn.wolfcode.luowowo.search.service.IStrategySearchService;
import cn.wolfcode.luowowo.search.template1.StrategyTemplate;
import cn.wolfcode.luowowo.search.vo.StatisVO;
import com.alibaba.dubbo.config.annotation.Service;
import org.apache.commons.collections.map.HashedMap;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregation;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.TermsValuesSourceBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

import java.util.*;

/**
 * Created by Administrator on 2019/7/15.
 */
@Service
public class StrategySearchServiceImpl implements IStrategySearchService{
    @Autowired
    private ElasticsearchTemplate template;
    @Autowired
    private IStrategyTemplateRepository dao;
    @Autowired
    private TransportClient client;

    @Override
    public void creatIndex() {
        template.createIndex(StrategyTemplate.class);
        template.getMapping(StrategyTemplate.class);
    }

    @Override
    public void save(StrategyTemplate template) {
        dao.save(template);
    }

    @Override
    public List<StatisVO> queryStrategyCondition(int conditionType) {
        List<CompositeValuesSourceBuilder<?>> sources = new ArrayList<>();
        //构建分组字段对象
        TermsValuesSourceBuilder idSource = new TermsValuesSourceBuilder("id");  //名字
        idSource.field("themeId");  //分组字段
        idSource.missingBucket(true);  //忽略不满足条件bucket

        TermsValuesSourceBuilder nameSource = new TermsValuesSourceBuilder("name");  //名字
        nameSource.field("themeName");  //分组字段
        nameSource.missingBucket(true);  //忽略不满足条件bucket

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if (conditionType== SearchQueryObject.CONDITION_TYPE_ABROAD){
            idSource.field("countryId");
            nameSource.field("countryName");
            boolQuery.mustNot(QueryBuilders.termQuery("countryId",1));
        }
        if (conditionType==SearchQueryObject.CONDITION_TYPE_UN_ABROAD){
            idSource.field("provinceId");
            nameSource.field("provinceName");
            boolQuery.must(QueryBuilders.termQuery("countryId",1));
        }
        if (conditionType==SearchQueryObject.CONDITION_TYPE_THEME){
            idSource.field("themeId");
            nameSource.field("themeName");
        }

        sources.add(idSource);
        sources.add(nameSource);


        //参数1:分组名称
        //参数2:分组字段集合
        CompositeAggregationBuilder builder = new CompositeAggregationBuilder("conditionGroup", sources);

        //查询请求对象: 设置索引
        SearchRequest request = new SearchRequest(StrategyTemplate.INDEX_NAME);
        //设置类型
        request.types(StrategyTemplate.TYPE_NAME);
        request.source(new SearchSourceBuilder()
                .aggregation(builder)
                .query(boolQuery)
                .size(0)
        );

        //请求发起
        SearchResponse response = this.client.search(request).actionGet();

        Aggregations aggregations = response.getAggregations();
        //聚合查询分组对象
        CompositeAggregation compositeAggregation = aggregations.get("conditionGroup");

        //结果封装
        List<? extends CompositeAggregation.Bucket> buckets = compositeAggregation.getBuckets();
        List<StatisVO> vos = new ArrayList<>();
        for (CompositeAggregation.Bucket bucket : buckets) {
            StatisVO  vo  = new StatisVO();
            Map<String, Object> key = bucket.getKey();
            vo.setId(Long.valueOf(key.get("id").toString()));
            vo.setName(key.get("name").toString());
            vo.setCount(bucket.getDocCount());
            vos.add(vo);
        }
        //排序
        Collections.sort(vos, new Comparator<StatisVO>() {
            @Override
            public int compare(StatisVO o1, StatisVO o2) {
                return o2.getCount().compareTo(o1.getCount());
            }
        });
        return vos;
    }

    @Override
    public Page<StrategyTemplate> query(SearchQueryObject qo) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (qo.getType()== SearchQueryObject.CONDITION_TYPE_ABROAD){
            boolQuery.must(QueryBuilders.termQuery("countryId",qo.getTypeValue()));
        }
        if (qo.getType()==SearchQueryObject.CONDITION_TYPE_UN_ABROAD){
            boolQuery.must(QueryBuilders.termQuery("provinceId",qo.getTypeValue()));
        }
        if (qo.getType()==SearchQueryObject.CONDITION_TYPE_THEME){
            boolQuery.must(QueryBuilders.termQuery("themeId",qo.getTypeValue()));
        }

        Page<StrategyTemplate> page = dao.search(boolQuery, qo.getPageable());
        return page;
    }

    @Override
    public Page<StrategyTemplate> queryByDestId(SearchQueryObject qo) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        TermQueryBuilder query;
        if (qo.getDestId()!=-1){
            query=QueryBuilders.termQuery("destId", qo.getDestId());
            boolQuery.must(query);
        }
        return dao.search(boolQuery,qo.getPageablewithoutSort());
    }


    @Override
    public List<Map<String, Object>> queryThemesComends() {
        List<CompositeValuesSourceBuilder<?>> sources = new ArrayList<>();
        //构建分组字段对象
        TermsValuesSourceBuilder idSource = new TermsValuesSourceBuilder("id");  //名字
        idSource.field("themeId");  //分组字段
        idSource.missingBucket(true);  //忽略不满足条件bucket

        TermsValuesSourceBuilder nameSource = new TermsValuesSourceBuilder("name");  //名字
        nameSource.field("themeName");  //分组字段
        nameSource.missingBucket(true);  //忽略不满足条件bucket

        sources.add(idSource);
        sources.add(nameSource);


        //参数1:分组名称
        //参数2:分组字段集合
        CompositeAggregationBuilder builder = new CompositeAggregationBuilder("themeGroup", sources);

        //查询请求对象: 设置索引
        SearchRequest request = new SearchRequest(StrategyTemplate.INDEX_NAME);
        //设置类型
        request.types(StrategyTemplate.TYPE_NAME);
        request.source(new SearchSourceBuilder()
                .aggregation(builder)
                .size(0)
        );

        //请求发起
        SearchResponse response = this.client.search(request).actionGet();

        Aggregations aggregations = response.getAggregations();
        //聚合查询分组对象
        CompositeAggregation compositeAggregation = aggregations.get("themeGroup");

        //结果封装
        List<? extends CompositeAggregation.Bucket> buckets = compositeAggregation.getBuckets();
        List<StatisVO> vos = new ArrayList<>();
        for (CompositeAggregation.Bucket bucket : buckets) {
            StatisVO  vo  = new StatisVO();
            Map<String, Object> key = bucket.getKey();
            vo.setId(Long.valueOf(key.get("id").toString()));
            vo.setName(key.get("name").toString());
            vo.setCount(bucket.getDocCount());
            vos.add(vo);
        }
        //排序
        Collections.sort(vos, new Comparator<StatisVO>() {
            @Override
            public int compare(StatisVO o1, StatisVO o2) {
                return o2.getCount().compareTo(o1.getCount());
            }
        });
        List<Map<String,Object>> data = new ArrayList<>();
        Map<String,Object> map;
        for (StatisVO themeVo : vos) {
            List<StatisVO> destVos = queryDestByThemeId(themeVo.getId());
            map = new HashedMap();
            map.put("themeVo",themeVo);//主题
            map.put("destVos",destVos);
            data.add(map);
        }
        return data;

    }

    private List<StatisVO> queryDestByThemeId(Long themeId) {
        List<StatisVO> list = new ArrayList<>();
        Iterable<StrategyTemplate> dests = dao.search(QueryBuilders.termQuery("themeId", themeId));
        //迭代遍历
        List<String> names = new ArrayList<>();
        dests.forEach(s->{
            if (!names.contains(s.getDestName())){
                StatisVO vo=new StatisVO();
                vo.setId(s.getDestId());
                vo.setName(s.getDestName());
                list.add(vo);
                names.add(vo.getName());
            }
        });
        return list;
    }
}
